﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlowBasis.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

namespace FlowBasis.EntityFramework
{
    public class EntityFrameworkUnitOfWork : IUnitOfWork, IDisposable
    {
        private Func<DbContext> dbContextFactory;
        private DbContext dbContext;

        public EntityFrameworkUnitOfWork(Func<DbContext> dbContextFactory)
        {
            this.dbContextFactory = dbContextFactory;                      
        }

        public void Dispose()
        {
            if (this.dbContext != null)
            {
                this.dbContext.Dispose();
                this.dbContext = null;
            }
        }

        private DbContext DbContextToUse
        {
            get
            {
                if (this.dbContext == null)
                {
                    this.dbContext = dbContextFactory();
                }
                
                return this.dbContext;
            }
        }
        
        public IQueryable GetAll(Type objectType)
        {
            return this.DbContextToUse.Set(objectType);
        }

        public IQueryable<T> GetAll<T>() where T : class
        {
            return this.DbContextToUse.Set<T>();
        }

        public object Find(Type objectType, params object[] keyValues)
        {
            return this.DbContextToUse.Set(objectType).Find(keyValues);
        }

        public T Find<T>(params object[] keyValues) where T : class
        {
            return this.DbContextToUse.Set<T>().Find(keyValues);
        }


        public object New(Type mappedType)
        {
            return Activator.CreateInstance(mappedType);
        }

        public T New<T>() where T : class, new()
        {
            return new T();
        }

        public void Insert(object value)
        {
            if (value != null)
            {
                this.DbContextToUse.Set(value.GetType()).Add(value);
            }
        }        

        public void Delete(object value)
        {
            if (value != null)
            {
                this.DbContextToUse.Set(value.GetType()).Remove(value);
            }
        }

        public void Commit()
        {
            if (this.dbContext != null)
            {
                this.dbContext.SaveChanges();
            }
        }

        public void Rollback()
        {
            if (this.dbContext != null)
            {
                this.dbContext.Dispose();
                this.dbContext = null;
            }
        }
    }
}
